package com.lyc.controller;

import com.lyc.bean.Message;
import com.lyc.mvc.ResponseBody;
import com.lyc.service.AdminService;
import com.lyc.util.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class AdminController {
    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        // 1.接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 2.调用service传递参数，并获取结果
        boolean result = AdminService.login(username, password);
        // 3.根据结果，准备不同的返回数据
        Message message = null;
        if (result){
            message = new Message("登录成功",0);// {result:"登录成功", status:0}
            // 登录时间和ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTime(username, date, ip);
            request.getSession().setAttribute("adminUserName","username");
        }else {
            message = new Message("登录失败",-1);// {result:"登录失败", status:-1}
        }
        // 4.将数据转换为JSON
        String json = JSONUtil.toJSON(message);
        // 5.将JSON返回给ajax
        return json;
    }
}
